<script setup lang="tsx">
import { reactive, onMounted } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessage } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { useRouter } from 'vue-router'
import { prePasswordApi, changePasswordApi } from '@/api/user'
import { smsSendApi } from '@/api/common'
import { useIntervalFn } from '@vueuse/core'

const { go } = useRouter()

const { t } = useI18n()

const time = ref(0)
const { pause, resume } = useIntervalFn(
  () => {
    time.value--
    if (time.value <= 0) {
      pause()
    }
  },
  1000,
  undefined
)

const smsSend = async () => {
  if (preData.value && preData.value.mobile.length) {
    if (time.value <= 0) {
      const res = await smsSendApi(preData.value.mobile, 4)
      ElMessage.success(res.data || '发送成功')
      time.value = 60
      resume()
    }
  }
}

const rules = {
  oldPassword: [
    {
      validator: function (_, value, callback) {
        if (preData.value && !preData.value.firstSetPwdState) {
          if (!value) {
            callback('请输入旧密码')
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
  ],
  newPassword: [
    {
      validator: function (_, value, callback) {
        if (/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(value)) {
          callback()
        } else {
          callback('请输入8-16位，包含字母、数字的密码')
        }
      }
    }
  ],
  confirmNewPassword: [
    {
      validator: function (_, value, callback) {
        if (/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(value)) {
          getFormData().then((formData) => {
            if (formData.confirmNewPassword !== formData.newPassword) {
              callback('两次输入的密码不一致')
            } else {
              callback()
            }
          })
        } else {
          callback('请输入新密码，要求：8-16位，必须包含字母、数字')
        }
      }
    }
  ],
  smsCode: [
    {
      validator: function (_, value, callback) {
        if (preData.value && preData.value.businessState) {
          if (!value) {
            callback('请输入验证码')
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
  ]
}

const schema = reactive<FormSchema[]>([
  {
    field: 'oldPassword',
    label: '旧密码',
    component: 'Input',
    colProps: {
      span: 13
    },
    componentProps: {
      type: 'password',
      placeholder: '请输入旧密码，首次设置无需填写'
    }
  },
  {
    field: 'newPassword',
    label: '新密码',
    component: 'Input',
    colProps: {
      span: 13
    },
    componentProps: {
      type: 'password',
      placeholder: '请输入新密码，要求：8-16位，必须包含字母、数字'
    }
  },
  {
    field: 'confirmNewPassword',
    label: '确认新密码',
    component: 'Input',
    colProps: {
      span: 13
    },
    componentProps: {
      type: 'password',
      placeholder: '请确认新密码，要求：8-16位，必须包含字母、数字'
    }
  },
  {
    field: 'smsCode',
    label: '验证码',
    component: 'Input',
    hidden: true,
    colProps: {
      span: 13
    },
    componentProps: {
      placeholder: '请输入验证码',
      slots: {
        append: (
          <ElButton type="primary" onClick={smsSend}>
            {time.value <= 0 ? t('login.fetchCode') : `${time.value}s`}
          </ElButton>
        )
      }
    }
  },
  {
    field: 'action',
    colProps: {
      span: 13
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="ml-[80px]">
                <ElButton class="w-[88px] h-[40px] mr-5" onClick={toCancel}>
                  {t('common.cancel')}
                </ElButton>
                <ElButton
                  class="w-[88px] h-[40px]"
                  type="primary"
                  loading={loading.value}
                  onClick={toSubmit}
                >
                  {t('common.ok')}
                </ElButton>
              </div>
            </>
          )
        }
      }
    }
  }
])

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

const preData = ref<any>(null)
const prePasswordData = () => {
  prePasswordApi().then((res: any) => {
    if (res.code === 200) {
      preData.value = res.data
      // 商户
      if (preData.value && preData.value.businessState) {
        schema[3].hidden = false
      }
    }
  })
}

const loading = ref(false)

const goBack = () => {
  go(-1)
}

const toCancel = () => {
  goBack()
}

const toSubmit = async () => {
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<any>()

      try {
        const res = await changePasswordApi(formData)
        if (res && res.code === 200) {
          ElMessage.success('修改成功')
          // 返回
          goBack()
        } else {
          ElMessage.error(res.message)
        }
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  prePasswordData()
})
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <div class="mb-5">{{ t('common.changePassword') }}</div>
      <Form
        :schema="schema"
        :rules="rules"
        hide-required-asterisk
        size="large"
        @register="formRegister"
      />
    </ContentWrap>
  </div>
</template>
